/**
 */
package com.dingpeikeji.quickdeer.core.modules.distribution.web;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.dingpeikeji.quickdeer.core.common.persistence.Page;
import com.dingpeikeji.quickdeer.core.common.utils.DateUtils;
import com.dingpeikeji.quickdeer.core.common.utils.StringUtils;
import com.dingpeikeji.quickdeer.core.common.utils.excel.ExportExcel;
import com.dingpeikeji.quickdeer.core.common.web.BaseController;
import com.dingpeikeji.quickdeer.core.modules.distribution.entity.DistributionExInfo;
import com.dingpeikeji.quickdeer.core.modules.distribution.entity.DistributionInfo;
import com.dingpeikeji.quickdeer.core.modules.distribution.service.TDistributionService;
import com.dingpeikeji.quickdeer.core.modules.trip.entity.MealsInfo;
import com.dingpeikeji.quickdeer.mobile.entity.ExtractInfo;
import com.dingpeikeji.quickdeer.mobile.entity.OrderInfo;
import com.dingpeikeji.quickdeer.mobile.service.ExtractService;
import com.dingpeikeji.quickdeer.mobile.service.OrderService;
import com.dingpeikeji.quickdeer.modules.utils.ValidateTool;


/**
 * 分销Controller
 */
@Controller
@RequestMapping(value = "${adminPath}/distribution/tDistribution")
public class TDistributionController extends BaseController {
	DecimalFormat df2 = new DecimalFormat("#.00");//保留两位小数
	private Sheet sheet;
	@Autowired
	private TDistributionService tDistributionService;
	@Autowired
	private OrderService orderService;
	@Autowired
	private ExtractService extractService;
	private static float rate;
	
	@ModelAttribute
	public DistributionInfo get1(@RequestParam(required=false) String distributionId) {
		
		if (StringUtils.isNotBlank(distributionId)){
			return tDistributionService.get(distributionId);
		}else{
			return new DistributionInfo();
		}
	}
	
	@ModelAttribute
	public DistributionInfo get(@RequestParam(required = false) String id) {
		DistributionInfo entity = null;
		if (StringUtils.isNotBlank(id)) {
			entity = tDistributionService.get(id);
		}
		if (entity == null) {
			entity = new DistributionInfo();
		}
		return entity;
	}
	
	@RequestMapping(value = { "list", "" })
	public String list(DistributionInfo distributionInfo, HttpServletRequest request, HttpServletResponse response,
			Model model) {
		rate = Float.parseFloat(tDistributionService.getRate());
		Page<DistributionInfo> page = tDistributionService.findPage(new Page<DistributionInfo>(request, response),
				distributionInfo);
		model.addAttribute("page", page);
		model.addAttribute("distributionInfo", distributionInfo);
		return "modules/distribution/tDistributionList";
	}

	@RequestMapping(value = "check")
	public String form(DistributionInfo distributionInfo,HttpServletRequest request, Model model) throws Exception {
		List<OrderInfo> info=new ArrayList<OrderInfo>();
		ExtractInfo extractInfo =new ExtractInfo();
		String d =request.getParameter("createTime");
		double money=0;
		if(distributionInfo!=null){//未结算的申请
			//打款信息
			distributionInfo= tDistributionService.get(distributionInfo.getDistributionId());
			if(distributionInfo.getStatus().equals("0")){
			//订单详情部分
			info =orderService.getOrderList(distributionInfo.getUserId());
			long time =ValidateTool.getMonthFirstDay(d);//获取指定月的第一天
			for(int i=0;i<info.size();i++){
				if(info.get(i).getCreateDate().getTime()>=time||info.get(i).getIsBalance().equals("0")||info.get(i).getIsBalance().equals("1")){//如果计佣订单的完单时间大于本月第一天则不计算该记录
					info.remove(i);
					i--;
				}else{
					money+=Double.parseDouble(info.get(i).getDueAmount());
				}
			}
			}else if(distributionInfo.getStatus().equals("1")){//已结算
				info=tDistributionService.getWithdrawSettleById(distributionInfo.getDistributionId());
				for(int i=0;i<info.size();i++){
					money+=Double.parseDouble(info.get(i).getDueAmount());
				}
			}
		}
		model.addAttribute("distributionInfo", distributionInfo);
		model.addAttribute("tOderDetail", info);
		model.addAttribute("money", money == 0?'0':df2.format(money*rate));
		model.addAttribute("createTime", d);
		model.addAttribute("userId", distributionInfo.getUserId());
		return "modules/distribution/tDistributionForm";
	}

    @RequestMapping(value = "exportall", method=RequestMethod.POST)
    public String exportAllFile(String distributionId ,String userId,String createTime,HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes, Model model) {
    	DistributionExInfo ExInfo=new DistributionExInfo(); 
    	List<OrderInfo> info=new ArrayList<OrderInfo>();
    	ExtractInfo extractInfo =new ExtractInfo();
    	DistributionInfo distributionInfo = new DistributionInfo();
    	double money=0;
    	try {
            String fileName = "分销数据"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
             info =orderService.getOrderList(userId);
			long time =ValidateTool.getMonthFirstDay(createTime);//获取指定月的第一天
			for(int i=0;i<info.size();i++){
				if(info.get(i).getCreateDate().getTime()>=time||info.get(i).getIsBalance().equals("0")||info.get(i).getIsBalance().equals("1")){//如果计佣订单的完单时间大于本月第一天则不计算该记录
					info.remove(i);
					i--;
				}else{
					money+=Double.parseDouble(info.get(i).getDueAmount());
				}
			}
			//打款信息
			distributionInfo= tDistributionService.get(distributionId);
			
			//分两次塞入数据
			new ExportExcel("分销数据", OrderInfo.class).setDataList(info).setDataList(rate,money,distributionInfo).write(response, fileName).dispose();

    		return null;
		} catch (Exception e) {
			e.printStackTrace();
			//addMessage(redirectAttributes, "导出订单数据失败！失败信息："+e.getMessage());
		}
    	model.addAttribute("distributionInfo", distributionInfo);
    	model.addAttribute("tOderDetail", info);
		model.addAttribute("money", money == 0?'0':df2.format(money*rate));
		model.addAttribute("createTime",createTime);
		model.addAttribute("userId", userId);
		return "modules/distribution/tDistributionForm";
    }

    @RequestMapping(value = "edit")
	public String edit(DistributionInfo distributionInfo,HttpServletRequest request, Model model) throws Exception {
		List<OrderInfo> info=new ArrayList<OrderInfo>();
		ExtractInfo extractInfo =new ExtractInfo();
		String d =request.getParameter("createTime");
		double money=0;
		if(distributionInfo!=null){
			//订单详情部分
			info =orderService.getOrderList(distributionInfo.getUserId());
			long time =ValidateTool.getMonthFirstDay(d);//获取指定月的第一天
			for(int i=0;i<info.size();i++){
				if(info.get(i).getCreateDate().getTime()>=time||info.get(i).getIsBalance().equals("0")||info.get(i).getIsBalance().equals("1")){//如果计佣订单的完单时间大于本月第一天则不计算该记录
					info.remove(i);
					i--;
				}else{
					money+=Double.parseDouble(info.get(i).getDueAmount());
				}
			}
			distributionInfo= tDistributionService.get(distributionInfo.getDistributionId());
		}
		model.addAttribute("distributionInfo", distributionInfo);
		model.addAttribute("tOderDetail", info);
		model.addAttribute("money", df2.format(money*rate));
		model.addAttribute("createTime", d);
		model.addAttribute("userId", distributionInfo.getUserId());
		return "modules/distribution/tDistributionEdit";
	}
    
    @RequestMapping(value = "save")
   	public String save(DistributionInfo distributionInfo,HttpServletRequest request,HttpServletResponse response, Model model) throws Exception {
   		if(distributionInfo!=null){
   			int i=tDistributionService.updateById(distributionInfo);
   			if(i>0){//打款单号更新成功后更新订单表对应订单状态
   				distributionInfo=tDistributionService.get(distributionInfo.getDistributionId());
   				int j=orderService.updateOrderBalance(distributionInfo,"1");
   			}
   		}
   		
   		Page<DistributionInfo> page = tDistributionService.findPage(new Page<DistributionInfo>(request, response),
				distributionInfo);
		model.addAttribute("page", page);
		model.addAttribute("distributionInfo", distributionInfo); 
   		return "modules/distribution/tDistributionList";
   	}
    
    @RequestMapping(value = "rate")
	public String meals(MealsInfo info, HttpServletRequest request, HttpServletResponse response,
			Model model) {
		info.setRate(tDistributionService.getRate());
		model.addAttribute("info", info);
		return "modules/distribution/tRateEdit";
	}

	@RequestMapping(value = "saveRate")
	public String saveMeals(MealsInfo info, HttpServletRequest request, HttpServletResponse response,
			Model model) {
		int i=tDistributionService.updateRate(info.getRate());
		info.setRate(tDistributionService.getRate());
		model.addAttribute("info", info);
		return "modules/distribution/tRateEdit";
	}


}
